<?php
/**
 * Created by PhpStorm.
 * User: whwyy
 * Date: 2018/3/26 0026
 * Time: 10:22
 */

namespace wchat\qq;

use wchat\common\Result;
use wchat\common\Help;

class Recharge extends SmallProgram
{
    private float $money = 0;

    private string $orderNo;

    private array $data = [];

    private string $spill_create_ip = '';

    private string $uniformer = '/cgi-bin/pay/qpay_unified_order.cgi';

    protected string $host = 'qpay.qq.com';

    /**
     * @param string $value
     */
    public function setSpillCreateIp(string $value): void
    {
        $this->spill_create_ip = $value;
    }

    /**
     * @param int $money
     * @param string $orderNo
     * @param string $openId
     * @return Result
     * @throws
     */
    public function recharge(int $money, string $orderNo, string $openId = ''): Result
    {
        if ($money < 0) {
            return new Result(code: 500, message: '充值金额不能小于0.');
        }
        $this->money          = $money;
        $this->orderNo        = $orderNo;
        $this->data['openid'] = $openId;

        return $this->post('api.q.qq.com', $this->uniformer, $this->builder(), 'application/xml');
    }


    /**
     * @param string $prepay_id
     * @return string
     */
    public function reception(string $prepay_id): string
    {
        return Help::sign([
            'signType'  => $this->payConfig->getSignType(),
            'package'   => 'prepay_id=' . $prepay_id,
            'nonceStr'  => Help::random(32),
            'timestamp' => time()
        ], $this->payConfig->pay->qq->mchSecret, $this->payConfig->getSignType());
    }

    /**
     * @return string
     */
    protected function builder(): string
    {
        $data                    = [
            'appid'            => $this->payConfig->appId,
            'mch_id'           => $this->payConfig->pay->qq->mchId,
            'nonce_str'        => Help::random(32),
            'body'             => $this->payConfig->getBody(),
            'out_trade_no'     => $this->orderNo,
            'total_fee'        => $this->money,
            'spbill_create_ip' => $this->spill_create_ip,
            'notify_url'       => $this->payConfig->getNotifyUrl(),
            'trade_type'       => $this->payConfig->getTradeType(),
        ];
        $this->data              = array_merge($data, $this->data);
        $key                     = $this->payConfig->pay->qq->mchSecret;
        $sign_type               = $this->payConfig->getSignType();
        $this->data['sign_type'] = $this->payConfig->getSignType();
        $this->data['sign']      = Help::sign($this->data, $key, $sign_type);

        return Help::toXml($this->data);
    }
}
